﻿///***************************************************************
/// 시  스  템 : Updms.Etc
/// 단위시스템 : ETC
/// 계      층 : Presentation Layer
/// 프로그램명 : Etc1010m
/// 파  일  명 : Etc1010m.aspx.cs
/// 설      명 : 주소록관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-07-15 송시명   최초 작성
///***************************************************************
using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Etc.Exe;


namespace Updms.Etc
{
	public partial class Etc1010m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		public static readonly string PID = "Etc1010m";
		public static readonly string gs_path_info = "/updms/Etc/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Etc etc = new CommCode.Etc(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	// 검색1
		protected string kw2 = "";	// 검색2
		protected string kw3 = "";	// 검색3

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SelectProcess();
			}
			SetClientScriptNoPostBack();
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetGrpCd();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript, SetClientScriptNoPostBack

		private void SetClientScript()
		{
			//onKeyPress이벤트 (엔터검색)
			txt_search_nm.Attributes.Add("onkeypress", "enterSearch(event)");
			txt_search_contact_number.Attributes.Add("onkeypress", "enterSearch(event)");
		}

		//포스트백과 무관하게 이벤트 지정
		private void SetClientScriptNoPostBack()
		{
			//그룹
			cbl_search_grp_cd.Items[0].Attributes.Add("onclick", "checkBoxListCheck('cbl_search_grp_cd');");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))
					{
						kw1 = WebControlUtil.GetCheckBoxListValue(cbl_search_grp_cd, 1);
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						WebControlUtil.SetCheckBoxListValue(cbl_search_grp_cd, kw1);
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = txt_search_nm.Text.Trim();
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_nm.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = txt_search_contact_number.Text.Trim();
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						txt_search_contact_number.Text = kw3;
					}
					break;
				case "SEARCH":
					kw1 = WebControlUtil.GetCheckBoxListValue(cbl_search_grp_cd, 1);
					kw2 = txt_search_nm.Text.Trim();
					kw3 = txt_search_contact_number.Text.Trim();
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = WebControlUtil.GetCheckBoxListText(cbl_search_grp_cd, 1);
			lbl_search_keyword.Text = ls_kw1 + " / " + kw2 + " / " + kw3;
		}

		#endregion

		#region 마스터 Method (SetGrpCd)

		//그룹정보
		private void SetGrpCd()
		{
			etc.SetGrpCd(cbl_search_grp_cd);
			etc.SetGrpCd(ddl_grp_cd);

			cbl_search_grp_cd.Items.Insert(0, new ListItem(GetXmlMsg("STR_019"), "ALL"));	//전체선택
		}

		#endregion

		#region 디테일 Method (그룹이동)

		//그룹이동
		protected void ddl_move_grp_cd_SelectedIndexChanged(object sender, EventArgs e)
		{
			DataPack lo_dp = new DataPack();
			StringBuilder sb = new StringBuilder();
			bool ls_checked = false;

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					ls_checked = true;
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();

					sb.Append("<UPDMS_ETC_PERSON_MGT>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_ETC_PERSON_MGT>");
				}
			}
			sb.Append("</UPDMS>");

			if (ls_checked)
			{
				MoveProcess(sb.ToString());
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_074");	//이동할 항목을 선택하세요
			}
			SearchProcess();
		}

		#endregion	

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, MoveProcess, SearchProcess)

		// 조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;
			
			//검색
			lo_dp.AddProperty("ls_grp_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_contact_number", typeof(string), kw3);

			using (Etc1010m_NT _Etc1010m_NT = new Etc1010m_NT())
			{
				li_row_count = _Etc1010m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Etc1010m_NT.SelectProcess(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			string search_condition = "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&page=";

			Pager pager = new Pager(this, ref lbl_page);
			pager.PageNavigation(
				li_cur_page,
				li_page_count,
				gs_path_info + search_condition);
				
			//결과출력(키워드, 검색행수)
			ShowKeywordLabel();
			lbl_result_count.Text = li_row_count.ToString("#,###,##0");

			//즐겨찾기
			ibtn_favorite.Attributes.Add("onclick", "javascript:goFavoriteSearchPage('" + PID + "','" + search_condition + "');return false;");
		}

		//저장
		private void InsertProcess()
		{
			using (Etc1010m_RT _Etc1010m_RT = new Etc1010m_RT())
			{
				int li_return = _Etc1010m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Etc1010m_RT _Etc1010m_RT = new Etc1010m_RT())
			{
				int li_return = _Etc1010m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);
				
				SearchProcess();
			} 
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Etc1010m_RT _Etc1010m_RT = new Etc1010m_RT())
			{
				int li_return = _Etc1010m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//이동
		private void MoveProcess(string ls_xml)
		{
			DataPack lo_dp = new DataPack();
			lo_dp.AddProperty("ls_xml", typeof(string), ls_xml);
			lo_dp.AddProperty("ls_tobe_grp_cd", typeof(string), ddl_move_grp_cd.SelectedValue);
			lo_dp.AddProperty("ls_user_id", typeof(string), USER_ID);

			using (Etc1010m_RT _Etc1010m_RT = new Etc1010m_RT())
			{
				int li_return = _Etc1010m_RT.SetGrpCdBySeq(lo_dp);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_013" : "MSG_ERR_132";	//이동되었습니다:이동할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		// SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("Seq",				typeof(string), lbl_pk.Text);
			lo_dp.AddProperty("Grp_Cd",				typeof(string), ddl_grp_cd.SelectedValue);
			lo_dp.AddProperty("Nm",					typeof(string), txt_nm.Text);
			lo_dp.AddProperty("Cell_Phone",			typeof(string), ConversionUtil.DefaultValue(txt_cell_phone.Text));
			lo_dp.AddProperty("Home_Phone",			typeof(string), ConversionUtil.DefaultValue(txt_home_phone.Text));
			lo_dp.AddProperty("BirthDay",			typeof(string), ConversionUtil.DefaultValue(txt_birthday.Text));
			lo_dp.AddProperty("Email",				typeof(string), ConversionUtil.DefaultValue(txt_email.Text));
			lo_dp.AddProperty("Zip_Cd",				typeof(string), ConversionUtil.DefaultValue(txt_zip_cd.Text));
			lo_dp.AddProperty("Address",			typeof(string), ConversionUtil.DefaultValue(txt_address.Text));
			lo_dp.AddProperty("Memo",				typeof(string), ConversionUtil.DefaultValue(txt_memo.Text));
			lo_dp.AddProperty("Latitude",			typeof(string), ConversionUtil.DefaultValue(txt_latitude.Text, ""));
			lo_dp.AddProperty("Longitude",			typeof(string), ConversionUtil.DefaultValue(txt_longitude.Text, ""));
			lo_dp.AddProperty("Use_Yn",				typeof(string), rbl_use_yn.SelectedValue);
			lo_dp.AddProperty("Create_User",		typeof(string), USER_ID);
			lo_dp.AddProperty("Create_Dt",			typeof(string), "");
			lo_dp.AddProperty("Update_User",		typeof(string), USER_ID);
			lo_dp.AddProperty("Update_Dt",			typeof(string), "");

			return lo_dp;
		}
		
		//ClearValue
		private void ClearValue()
		{
			// Source
			lbl_pk.Text = "";
			h_no.Value = "";
			ddl_grp_cd.SelectedIndex = 0;
			txt_nm.Text = "";
			txt_cell_phone.Text = "";
			txt_home_phone.Text = "";
			txt_birthday.Text = "";
			txt_email.Text = "";
			txt_zip_cd.Text = "";
			txt_address.Text = "";
			txt_memo.Text = "";
			txt_latitude.Text = "";
			txt_longitude.Text = "";
			rbl_use_yn.SelectedIndex = 0;
			ddl_move_grp_cd.Visible = false;
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			//페이지모드 처리
			string ls_class = String.IsNullOrEmpty(lbl_pk.Text) ? "sbtn sbtn_mode_i" : "sbtn sbtn_mode_u";
			string ls_title = String.IsNullOrEmpty(lbl_pk.Text) ? "입력" : "수정";
			btn_chg_mode.Attributes.Add("class", ls_class);
			btn_chg_mode.Attributes.Add("title", ls_title);

			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion
		
		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				//사용여부
				e.Row.Cells[16].Attributes.Add("class", (e.Row.Cells[16].Text == "Y") ? "color_darkred" : "color_gray");
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 4);
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{		
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();																	//0.체크박스
			h_no.Value					= row.Cells[1].Text.ToString();										//1.번호
			lbl_pk.Text					= gv.DataKeys[row.RowIndex].Values["Seq"].ToString();				//2.Seq
			ddl_grp_cd.SelectedValue	= gv.DataKeys[row.RowIndex].Values["Grp_Cd"].ToString();			//3.Grp_Cd
			//																								//4.Grp_Cd_Nm
			txt_nm.Text					= lbtn_rc.Text;														//5.Nm (template)
			txt_cell_phone.Text			= row.Cells[6].Text.Trim();											//6.Cell_Phone
			txt_home_phone.Text			= row.Cells[7].Text.Trim();											//7.Home_Phone
			txt_birthday.Text			= gv.DataKeys[row.RowIndex].Values["BirthDay"].ToString();			//8.BirthDay
			txt_email.Text				= gv.DataKeys[row.RowIndex].Values["Email"].ToString();				//9.Email
			txt_zip_cd.Text				= gv.DataKeys[row.RowIndex].Values["Zip_Cd"].ToString();			//10.Zip_Cd
			txt_address.Text			= gv.DataKeys[row.RowIndex].Values["Address"].ToString();			//11.Address
			txt_memo.Text				= row.Cells[12].Text.Trim();										//12.Memo
																											//13.NaverMap_Link
			txt_latitude.Text			= gv.DataKeys[row.RowIndex].Values["Latitude"].ToString();			//14.Latitude
			txt_longitude.Text			= gv.DataKeys[row.RowIndex].Values["Longitude"].ToString();			//15.Longitude
			rbl_use_yn.SelectedValue	= row.Cells[16].Text.Trim();										//16.Use_Yn
		}

		#endregion

		#region 버튼이벤트
		
		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}
		
		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_ETC_PERSON_MGT", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();

					sb.Append("<UPDMS_ETC_PERSON_MGT>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_ETC_PERSON_MGT>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//이동
		protected void ibtn_move_Click(object sender, EventArgs e)
		{
			ddl_move_grp_cd.Visible = true;

			etc.SetGrpCd(ddl_move_grp_cd);
			ddl_move_grp_cd.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}
		
		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_grp_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_contact_number", typeof(string), kw3);

			using (Etc1010m_NT _Etc1010m_NT = new Etc1010m_NT())
			{
				li_row_count = _Etc1010m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Etc1010m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//디테일 초기화
		protected void lbtn_init_detail_Click(object sender, EventArgs e)
		{
			ClearValue();
		}

		//페이지모드변경
		protected void lbtn_chg_mode_Click(object sender, EventArgs e)
		{
			h_no.Value = "";
			lbl_pk.Text = "";
		}
		
		#endregion
	
	}
}
